package com.example.erhuo.fragment;

import androidx.databinding.DataBindingUtil;

import com.example.erhuo.PersonInformation;
import com.example.erhuo.R;
import com.example.erhuo.activity.BoughtActivity;
import com.example.erhuo.activity.LoginActivity;
import com.example.erhuo.activity.MainActivity;
import com.example.erhuo.activity.MyInformationActivity;
import com.example.erhuo.activity.MyLikeActivity;
import com.example.erhuo.activity.SoldActivity;
import com.example.erhuo.activity.WantMeActivity;
import com.example.erhuo.api.NetAPI;
import com.example.erhuo.databinding.MyFragmentBinding;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;


import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MyFragment extends Fragment implements View.OnClickListener {

    private MyViewModel myViewModel;
    private String token = null;
    private static String TAG = "MyFragment";
    private MyFragmentBinding binding;

    private Button button;
    private TextView textName;
    private TextView textId;

    public static MyFragment newInstance() {
        return new MyFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        myViewModel = ViewModelProviders.of(getActivity()).get(MyViewModel.class);

        binding = DataBindingUtil.inflate(inflater, R.layout.my_fragment, container, false);
        binding.setData(myViewModel);
        binding.setLifecycleOwner(getActivity());

        initFragment();
        setFragment();
        token = MainActivity.token;
        if (token != null) {
            initPersonInformation(token);
        }
        if (!myViewModel.userIsLogin()) {
            button.setClickable(false);
            button.setBackgroundColor(getResources().getColor(R.color.grey));
        } else {
            button.setClickable(true);
            button.setBackgroundColor(getResources().getColor(R.color.green_200));
        }
        Log.i(TAG, "" + myViewModel.userIsLogin());
        //Log.i(TAG, token);


        return binding.getRoot();
        //return inflater.inflate(R.layout.my_fragment, container, false);
    }

    private void initFragment() {
        button = getActivity().findViewById(R.id.main_button_add);
        textName = binding.myUserName;
        textId = binding.myUserId;
    }

    private void setFragment() {
        binding.myButtonInformation.setOnClickListener(this);
        binding.myButtonLike.setOnClickListener(this);
        binding.myButtonWant.setOnClickListener(this);
        binding.myButtonBought.setOnClickListener(this);
        binding.myButtonSold.setOnClickListener(this);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {

        // TODO: Use the ViewModel
        super.onActivityCreated(savedInstanceState);
        token = MainActivity.token;
    }


    public boolean isLogin() {
        return myViewModel.userIsLogin();
    }

    private void initPersonInformation(String token) {
        Callback callback = new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "获取个人信息失败");
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "获取个人信息失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String information = response.body().string();
                Log.i(TAG, information);
                JSONObject json = null;
                try {
                    json = new JSONObject(information);
                    String code = json.getString("code");
                    switch (code) {
                        case "200": {
                            String data = json.getString("data");
                            JSONObject jsonData = new JSONObject(data);
                            String nickname = jsonData.getString("name");
                            String username = jsonData.getString("username");
                            String email = jsonData.getString("email");
                            PersonInformation person = new PersonInformation(username, nickname, email);
                            myViewModel.setPersonInformation(person);
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    button.setClickable(true);
                                    button.setBackgroundColor(getResources().getColor(R.color.green_200));
                                    binding.myUserId.setText(myViewModel.getStudentId());
                                    binding.myUserName.setText(myViewModel.getUsername());
                                }
                            });
                            break;
                        }
                        default: {
                            Log.e(TAG, code);
                            break;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        NetAPI.get("api/profile", callback, token);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_button_information: {
                if (myViewModel.userIsLogin()) {
                    Intent intent = new Intent(getActivity(), MyInformationActivity.class);
                    intent.putExtra("token", myViewModel.getToken());
                    startActivity(intent);
                } else {
                    //没登陆，快去登录
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
                        }
                    });
                    Intent intentLogin = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intentLogin);
                }
                break;
            }
            case R.id.my_button_like: {
                if (MainActivity.token == null || MainActivity.token.equals("")) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }
                Intent intent = new Intent(getActivity(), MyLikeActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.my_button_want: {
                if (MainActivity.token == null || MainActivity.token.equals("")) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }
                Intent intent = new Intent(getActivity(), WantMeActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.my_button_bought: {
                if (MainActivity.token == null || MainActivity.token.equals("")) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }
                Intent intent = new Intent(getActivity(), BoughtActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.my_button_sold: {
                if (MainActivity.token == null || MainActivity.token.equals("")) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }
                Intent intent = new Intent(getActivity(), SoldActivity.class);
                startActivity(intent);
                break;
            }

        }
    }
}